package com.kuiniu.threeframe.client;

import com.alibaba.fastjson.JSON;
import com.kuiniu.threeframe.client.entity.AnalysisJsonData;
import com.kuiniu.threeframe.client.entity.Message;
import com.kuiniu.threeframe.client.timeout.MsgTimeoutManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.ChannelInputShutdownReadComplete;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private Client client;

    public NettyClientHandler(Client client) {
        this.client = client;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for (EventListener listener : client.getMsgListeners()) {
            listener.onConnected();
        }
    }

    /**
     * @param ctx
     * @author xiongchuan on 2019/4/28 16:10
     * @DESCRIPTION: 有服务端端终止连接服务器会触发此函数
     * @return: void
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        for (EventListener listener : client.getMsgListeners()) {
            listener.onDisconnected();
        }
    }

    private AnalysisJsonData analysisJsonData = new AnalysisJsonData("##", 4,
            new AnalysisJsonData.OnDataResult() {
                @Override
                public void onResult(String t) {
                    Message message = JSON.parseObject(t, Message.class);
                    client.getMsgTimeoutManager().remove(message);
                    for (EventListener listener : client.getMsgListeners()) {
                        listener.onMessage(message);
                    }
                }
            });

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof String) {
            analysisJsonData.addString((String) msg);
        }
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("长期没收到服务器推送数据");
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                System.out.println("长期未向服务器发送数据");
                //发送心跳包
                //ctx.writeAndFlush(MessageProto.getHeartMsg());
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                System.out.println("ALL");
            }
        } else if (evt instanceof ChannelInputShutdownReadComplete) {
            System.out.println("通道被服务端关闭了");
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.info("服务端发生异常【" + cause.getMessage() + "】");
        ctx.close();
    }

}
